package com.zh.recordscreen.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

import com.zh.recordscreen.service.ScreenRecordService;

/**
 * descrition:
 */
public class ConnectUtils {
    //录屏工具
    MediaProjectionManager mediaProjectionManager;
    MediaProjection mediaProjection;

    //获取录屏范围参数
    DisplayMetrics metrics;
    //录屏服务
    public  ScreenRecordService screenRecordService;
    private Activity mContext;
    private  ServiceConnection serviceConnection;
    private static ConnectUtils instance = null;
    private ConnectUtils(){}
    public static synchronized ConnectUtils getInstance(){
        if(instance == null) {
            instance = new ConnectUtils();
        }
        return instance;
    }
    public void init(Activity context){
        mContext = context;
        initServiceConnect();
    }

    public  void connectService(){
        //通过intent为中介绑定Service，会自动create
        Intent intent = new Intent(mContext, ScreenRecordService.class);
        //绑定过程连接，选择绑定模式
        mContext.bindService(intent,serviceConnection,mContext.BIND_AUTO_CREATE);

        Log.e("连接服务","====connectService===");
    }

    private void initServiceConnect(){
        serviceConnection = new ServiceConnection() {
            @SuppressLint("NewApi")
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.e("服务连接成功","====initServiceConnect===");

                //服务连接成功，需要通过Binder获取服务，达到Activity和Service通信的目的
                //获取Binder
                ScreenRecordService.ScreenRecordBinder binder = (ScreenRecordService.ScreenRecordBinder) iBinder;
                //通过Binder获取Service
                screenRecordService = binder.getScreenRecordService();
                //获取到服务，初始化录屏管理者
                mediaProjectionManager = (MediaProjectionManager) mContext.getSystemService(mContext.MEDIA_PROJECTION_SERVICE);
                //通过管理者，创建录屏请求，通过Intent
                Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
                //将请求码作为标识一起发送，调用该接口，需有返回方法
                mContext.startActivityForResult(captureIntent,1001);
                Log.e("连接服务","====onServiceConnected===");
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                //连接失败
                Log.e("服务连接失败","====onServiceDisconnected===");
                Toast.makeText(mContext,"录屏服务未连接成功，请重试！",Toast.LENGTH_SHORT).show();
            }
        };
    }
    @SuppressLint("NewApi")
    public void setMedia(int resultCode, Intent data){
        //从发送获得的数据和结果中获取该工具
        mediaProjection =
                mediaProjectionManager.getMediaProjection(resultCode, data);
        //将该工具给Service，并一起传过去需要录制的屏幕范围的参数
        if(screenRecordService != null){
            screenRecordService.setMediaProjection(mediaProjection);
            //获取录屏屏幕范围参数
            metrics = new DisplayMetrics();
            mContext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            screenRecordService.setConfig(metrics.widthPixels,metrics.heightPixels,metrics.densityDpi);
        }
    }

    public void startRecord(){
        if(screenRecordService != null && screenRecordService.isRunning()){
            Toast.makeText(mContext,"当前正在录屏，请不要重复点击哦！",Toast.LENGTH_SHORT).show();
        } else if(screenRecordService != null && !screenRecordService.isRunning()){
            //没有录制，就开始录制，弹出提示，返回主界面开始录制
            screenRecordService.startRecord();
            //返回主界面开始录制
//            setToBackground();
        } else if(screenRecordService == null){
            connectService();
        }
    }

    public void stopRecord(){
        if(screenRecordService != null && !screenRecordService.isRunning()){
            //没有在录屏，无法停止，弹出提示
            Log.e("停止录屏",screenRecordService+"====onServiceConnected==="+screenRecordService.isRunning());

            Toast.makeText(mContext,"您还没有录屏，无法停止，请先开始录屏吧！",Toast.LENGTH_SHORT).show();
        }else if(screenRecordService != null && screenRecordService.isRunning()){
            //正在录屏，点击停止，停止录屏
            mContext.unbindService(serviceConnection);
            screenRecordService.stopRecord();

        }
    }

    //返回主界面开始录屏，相当于home键
    private void setToBackground(){
        //主页面的Intent
        Intent home = new Intent(Intent.ACTION_MAIN);
        //设置清除栈顶的启动模式
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //匹配符号
        home.addCategory(Intent.CATEGORY_HOME);
        //转换界面，隐式匹配，显示调用
        mContext.startActivity(home);
    }



}
